package com.school.sports.service.Impl;

import com.school.sports.entity.ExceptionRecord;
import com.school.sports.service.ExceptionNotificationService;
import com.school.sports.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 异常通知服务实现类
 */
@Slf4j
@Service
public class ExceptionNotificationServiceImpl implements ExceptionNotificationService {

    @Autowired(required = false)
    private MessageService messageService;

    // 默认通知配置
    private final Map<String, Object> defaultNotificationConfig = new HashMap<>();

    public ExceptionNotificationServiceImpl() {
        // 初始化默认配置
        Map<String, Object> emailConfig = new HashMap<>();
        emailConfig.put("enabled", true);
        emailConfig.put("recipients", new String[]{"admin@example.com"});
        defaultNotificationConfig.put("email", emailConfig);

        Map<String, Object> systemMessageConfig = new HashMap<>();
        systemMessageConfig.put("enabled", true);
        systemMessageConfig.put("recipientRoles", new String[]{"管理员", "系统管理员"});
        defaultNotificationConfig.put("system_message", systemMessageConfig);

        Map<String, Object> severeExceptionConfig = new HashMap<>();
        severeExceptionConfig.put("enabled", true);
        severeExceptionConfig.put("immediate", true);
        severeExceptionConfig.put("channels", new String[]{"email", "system_message"});
        defaultNotificationConfig.put("severe_exception", severeExceptionConfig);
    }

    @Override
    public boolean sendExceptionNotification(ExceptionRecord exceptionRecord) {
        try {
            if (exceptionRecord == null) {
                log.warn("异常记录为空，无法发送通知");
                return false;
            }
            log.info("发送异常通知，异常ID：{}，异常类型：{}", exceptionRecord.getId(), exceptionRecord.getExceptionType());

            // 异步发送通知，避免阻塞主流程
            CompletableFuture.runAsync(() -> {
                try {
                    // 根据异常级别决定通知方式
                    if (exceptionRecord.getExceptionLevel() != null &&
                        exceptionRecord.getExceptionLevel().equals(ExceptionRecord.Level.SEVERE.getCode())) {
                        sendSevereExceptionNotification(exceptionRecord);
                    } else {
                        sendNormalExceptionNotification(exceptionRecord);
                    }
                } catch (Exception e) {
                    log.error("异步发送异常通知失败：{}", e.getMessage(), e);
                }
            });

            return true;
        } catch (Exception e) {
            log.error("发送异常通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendSevereExceptionNotification(ExceptionRecord exceptionRecord) {
        try {
            if (exceptionRecord == null) {
                log.warn("异常记录为空，无法发送严重异常通知");
                return false;
            }
            log.warn("发送严重异常通知，异常ID：{}", exceptionRecord.getId());

            Object configObj = getNotificationConfig("severe_exception");
            if (!(configObj instanceof Map)) {
                return true;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> config = (Map<String, Object>) configObj;
            Object enabledObj = config.get("enabled");
            if (enabledObj instanceof Boolean && !(Boolean) enabledObj) {
                return true;
            }

            Object channelsObj = config.get("channels");
            String[] channels;
            if (channelsObj instanceof String[]) {
                channels = (String[]) channelsObj;
            } else if (channelsObj instanceof java.util.List) {
                java.util.List<?> list = (java.util.List<?>) channelsObj;
                channels = list.toArray(new String[0]);
            } else {
                channels = new String[0];
            }
            for (String channel : channels) {
                try {
                    switch (channel) {
                        case "email":
                            sendEmailNotification(exceptionRecord, true);
                            break;
                        case "system_message":
                            sendSystemMessageNotification(exceptionRecord, true);
                            break;
                        default:
                            log.warn("未知的通知渠道：{}", channel);
                    }
                } catch (Exception e) {
                    log.error("通过渠道{}发送通知失败：{}", channel, e.getMessage());
                }
            }

            return true;
        } catch (Exception e) {
            log.error("发送严重异常通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendExceptionHandledNotification(ExceptionRecord exceptionRecord) {
        try {
            log.info("发送异常处理通知，异常ID：{}", exceptionRecord.getId());

            // 发送系统消息给处理人
            String title = "异常处理完成通知";
            String content = String.format("异常已处理完成\n异常ID：%d\n异常类型：%s\n处理人：%s\n处理时间：%s\n解决方案：%s",
                    exceptionRecord.getId(),
                    exceptionRecord.getExceptionType(),
                    exceptionRecord.getHandlerName(),
                    exceptionRecord.getHandleTime() != null ?
                        exceptionRecord.getHandleTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : "",
                    exceptionRecord.getSolution());

            // 发送给管理员
            if (messageService != null) {
                messageService.sendMessageToRoles(title, content, "系统通知", new String[]{"管理员", "系统管理员"});
            } else {
                log.warn("消息服务未初始化，无法发送异常处理通知");
            }

            return true;
        } catch (Exception e) {
            log.error("发送异常处理通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendExceptionStatisticsReport(Object reportData, String reportType) {
        try {
            log.info("发送异常统计报告，报告类型：{}", reportType);

            String title = String.format("异常统计报告 - %s", reportType);
            String content = generateStatisticsReportContent(reportData, reportType);

            // 发送给管理员
            if (messageService != null) {
                messageService.sendMessageToRoles(title, content, "系统通知", new String[]{"管理员", "系统管理员"});
            } else {
                log.warn("消息服务未初始化，无法发送异常处理通知");
            }

            return true;
        } catch (Exception e) {
            log.error("发送异常统计报告失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Object getNotificationConfig(String notificationType) {
        return defaultNotificationConfig.getOrDefault(notificationType, new HashMap<>());
    }

    @Override
    public boolean updateNotificationConfig(String notificationType, Object config) {
        try {
            defaultNotificationConfig.put(notificationType, config);
            log.info("更新通知配置成功，通知类型：{}", notificationType);
            return true;
        } catch (Exception e) {
            log.error("更新通知配置失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean testNotification(String notificationType) {
        try {
            log.info("测试通知功能，通知类型：{}", notificationType);

            // 创建测试异常记录
            ExceptionRecord testRecord = new ExceptionRecord();
            testRecord.setId(0L);
            testRecord.setExceptionType("测试异常");
            testRecord.setExceptionDesc("这是一个测试异常，用于验证通知功能是否正常工作");
            testRecord.setOccurTime(LocalDateTime.now());
            testRecord.setExceptionLevel(ExceptionRecord.Level.SLIGHT.getCode());
            testRecord.setHandleStatus(ExceptionRecord.Status.PENDING.getCode());

            switch (notificationType) {
                case "email":
                    return sendEmailNotification(testRecord, false);
                case "system_message":
                    return sendSystemMessageNotification(testRecord, false);
                case "severe_exception":
                    return sendSevereExceptionNotification(testRecord);
                default:
                    log.warn("未知的通知类型：{}", notificationType);
                    return false;
            }
        } catch (Exception e) {
            log.error("测试通知功能失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送普通异常通知
     */
    private boolean sendNormalExceptionNotification(ExceptionRecord exceptionRecord) {
        try {
            // 发送系统消息
            Object systemConfigObj = getNotificationConfig("system_message");
            if (!(systemConfigObj instanceof Map)) {
                return true;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> config = (Map<String, Object>) systemConfigObj;
            Object systemEnabledObj = config.get("enabled");
            if (systemEnabledObj instanceof Boolean && (Boolean) systemEnabledObj) {
                sendSystemMessageNotification(exceptionRecord, false);
            }

            // 发送邮件通知
            Object emailConfigObj = getNotificationConfig("email");
            if (!(emailConfigObj instanceof Map)) {
                return true;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> emailConfig = (Map<String, Object>) emailConfigObj;
            Object emailEnabledObj = emailConfig.get("enabled");
            if (emailEnabledObj instanceof Boolean && (Boolean) emailEnabledObj) {
                sendEmailNotification(exceptionRecord, false);
            }

            return true;
        } catch (Exception e) {
            log.error("发送普通异常通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送邮件通知
     */
    private boolean sendEmailNotification(ExceptionRecord exceptionRecord, boolean isSevere) {
        try {
            // 这里可以实现邮件发送逻辑
            // 由于项目中没有邮件服务，这里只是模拟实现
            log.info("发送邮件通知：异常类型={}, 严重程度={}",
                    exceptionRecord.getExceptionType(),
                    isSevere ? "严重" : "普通");

            // 实际实现可以使用JavaMail或其他邮件服务
            String subject = String.format("[%s]系统异常通知", isSevere ? "严重" : "普通");
            String content = generateEmailContent(exceptionRecord, isSevere);

            // 这里应该调用邮件服务发送邮件
            // emailService.send(subject, content, recipients);

            return true;
        } catch (Exception e) {
            log.error("发送邮件通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送系统消息通知
     */
    private boolean sendSystemMessageNotification(ExceptionRecord exceptionRecord, boolean isSevere) {
        try {
            String title = String.format("[%s]系统异常通知", isSevere ? "严重" : "普通");
            String content = generateSystemMessageContent(exceptionRecord, isSevere);

            Object messageConfigObj = getNotificationConfig("system_message");
            if (!(messageConfigObj instanceof Map)) {
                return false;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> config = (Map<String, Object>) messageConfigObj;
            Object recipientRolesObj = config.get("recipientRoles");
            String[] recipientRoles;
            if (recipientRolesObj instanceof String[]) {
                recipientRoles = (String[]) recipientRolesObj;
            } else if (recipientRolesObj instanceof java.util.List) {
                java.util.List<?> list = (java.util.List<?>) recipientRolesObj;
                recipientRoles = list.toArray(new String[0]);
            } else {
                recipientRoles = new String[0];
            }

            if (messageService != null) {
                return messageService.sendMessageToRoles(title, content, "紧急通知", recipientRoles);
            } else {
                log.warn("消息服务未初始化，无法发送系统消息通知");
                return false;
            }
        } catch (Exception e) {
            log.error("发送系统消息通知失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 生成邮件内容
     */
    private String generateEmailContent(ExceptionRecord exceptionRecord, boolean isSevere) {
        StringBuilder content = new StringBuilder();
        content.append("系统发生异常，详情如下：\n\n");
        content.append(String.format("异常ID：%d\n", exceptionRecord.getId()));
        content.append(String.format("异常类型：%s\n", exceptionRecord.getExceptionType()));
        content.append(String.format("异常描述：%s\n", exceptionRecord.getExceptionDesc()));
        content.append(String.format("发生时间：%s\n",
                exceptionRecord.getOccurTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        content.append(String.format("发生地点：%s\n", exceptionRecord.getOccurLocation()));
        content.append(String.format("异常级别：%s\n", exceptionRecord.getExceptionLevelDesc()));
        content.append(String.format("操作用户：%s\n", exceptionRecord.getOperatorName()));
        content.append(String.format("用户IP：%s\n", exceptionRecord.getUserIp()));

        if (isSevere) {
            content.append("\n⚠️ 这是一个严重异常，请立即处理！\n");
        }

        content.append("\n请登录系统查看详细信息并及时处理。");

        return content.toString();
    }

    /**
     * 生成系统消息内容
     */
    private String generateSystemMessageContent(ExceptionRecord exceptionRecord, boolean isSevere) {
        StringBuilder content = new StringBuilder();
        content.append(String.format("系统发生%s异常：%s",
                isSevere ? "严重" : "普通",
                exceptionRecord.getExceptionType()));

        if (exceptionRecord.getExceptionDesc() != null && exceptionRecord.getExceptionDesc().length() > 50) {
            content.append("\n").append(exceptionRecord.getExceptionDesc().substring(0, 50)).append("...");
        } else if (exceptionRecord.getExceptionDesc() != null) {
            content.append("\n").append(exceptionRecord.getExceptionDesc());
        }

        content.append(String.format("\n发生时间：%s",
                exceptionRecord.getOccurTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));

        if (isSevere) {
            content.append("\n\n请立即处理！");
        }

        return content.toString();
    }

    /**
     * 生成统计报告内容
     */
    private String generateStatisticsReportContent(Object reportData, String reportType) {
        StringBuilder content = new StringBuilder();
        content.append(String.format("异常统计报告（%s）\n\n", reportType));

        // 这里应该根据reportData生成详细的统计内容
        content.append("报告生成时间：").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        content.append("请登录系统查看详细统计信息。");

        return content.toString();
    }
}